package lk.mrt.cse.wihidum.router.processor;

import org.apache.log4j.Logger;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.client.Options;
import org.apache.axis2.addressing.EndpointReference;

public class UnsubscribeProcessor {

    private static final Logger logger = Logger.getLogger (UnsubscribeProcessor.class);

    public String unsusbcribe(String listenerServiceAddress, String clientID, String filterTopic) {
        OMFactory factory = OMAbstractFactory.getOMFactory();

        OMElement messageElement = factory.createOMElement("UnsubscriptionRequest", null);

        OMElement actionElement = factory.createOMElement("Action", null);
        actionElement.setText("unsubscribe");
        messageElement.addChild(actionElement);

        OMElement subscriptionIDElement = factory.createOMElement("subscriptionID", null);
        subscriptionIDElement.setText(clientID);
        messageElement.addChild(subscriptionIDElement);

        OMElement topicElement = factory.createOMElement("topic", null);
        topicElement.setText(filterTopic);
        messageElement.addChild(topicElement);

        try
        {
            ServiceClient serviceClient = new ServiceClient();
            Options options = new Options();
            options.setTo(new EndpointReference(listenerServiceAddress));
            options.setAction("unsubscribe");
            serviceClient.setOptions(options);
            OMElement responseElement = serviceClient.sendReceive(messageElement);
            if(responseElement!=null)
            {
                logger.info("Unsubscription sent to broker service successfully");                
                return "Unsubscription completed successfully";
            }
            else
                return "No response for unsubscription";
        }
        catch (Exception ex)
        {
            return null;
        }
    }
}
